package com.liulin.cdse.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liulin.cdse.entity.Manager;
import com.liulin.cdse.exception.AccountExistException;
import com.liulin.cdse.service.ManagerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Slf4j
@Controller
@RequestMapping("admin/manager")
public class ManagerController {
    @Autowired
    private ManagerService managerService;

    @GetMapping("add")
    public String add() {
        return "manager_add";
    }

    @PostMapping("add")
    public String add(Manager manager, Model model) {
        manager.setStatus("y");
        try {
            managerService.add(manager);
        } catch (AccountExistException e) {
            model.addAttribute("msg", "用户名重复");
            return "manager_add";
        }
        model.addAttribute("msg", "添加成功");
        return "manager_add";
    }

    @GetMapping("list")
    public String list(Model model) {
        List<Manager> managers = managerService.list();
        model.addAttribute("managers", managers);
        return "manager_list";
    }

    @GetMapping("update/{id}")
    public String update(@PathVariable int id, Model model) {
        Manager manager = managerService.getById(id);
        model.addAttribute("manager", manager);
        return "manager_update";
    }

    @PostMapping("update")
    public String update(Manager manager, RedirectAttributes redirectAttributes) {
        log.debug("manager:{}", manager);
        QueryWrapper<Manager> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", manager.getAccount());
        if(managerService.getOne(queryWrapper) == null) {
            managerService.updateById(manager);
            return "redirect:/admin/manager/list";
        }
        redirectAttributes.addFlashAttribute("msg","账号重复");
        return "redirect:/admin/manager/update/"+manager.getId();
    }

    @GetMapping("del/{id}")
    public String del(@PathVariable int id){
        managerService.removeById(id);
        return "redirect:/admin/manager/list";
    }

}
